package com.guigu.springcloud.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.springcloud.common.CommonResult;
import com.guigu.springcloud.entities.Payment;
import com.guigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    private final PaymentService paymentService;

    private final DiscoveryClient discoveryClient;

    public PaymentController(PaymentService paymentService, DiscoveryClient discoveryClient) {
        this.paymentService = paymentService;
        this.discoveryClient = discoveryClient;
    }

    @Value(value = "${server.port}")
    private String serverPort;

    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment) {
        log.info("server port: {}", serverPort);
        int result = paymentService.create(payment);
        // 返回写入数据的ID
        log.info("写入数据结果：{}", payment.getId());
        if (result > 0) {
            return new CommonResult(200, "写入数据库成功", result);
        } else {
            return new CommonResult(500, "写入数据库失败", null);
        }
    }

    @GetMapping(value = "/get/{id}")
    public CommonResult create(@PathVariable("id") Long id) {
        log.info("server port: {}", serverPort);
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            return new CommonResult(200, "查询数据成功,server:" + serverPort, payment);
        } else {
            return new CommonResult(500, "查询数据失败", null);
        }
    }

    @GetMapping(value = "/discovery")
    public CommonResult getDiscovery() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        return new CommonResult(200, "查询成功", objectMapper.writeValueAsString(services));
    }
}
